package com.dwx.guli.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dwx.guli.service.edu.entity.Chapter;
import com.dwx.guli.service.edu.entity.Video;
import com.dwx.guli.service.edu.entity.vo.ChapterVo;
import com.dwx.guli.service.edu.entity.vo.VideoVo;
import com.dwx.guli.service.edu.mapper.ChapterMapper;
import com.dwx.guli.service.edu.mapper.VideoMapper;
import com.dwx.guli.service.edu.service.ChapterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dwx.guli.service.edu.service.VideoService;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author dwx
 * @since 2021-06-30
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    @Autowired
    VideoMapper videoMapper;
    @Override
    public boolean removeChapterById(String id) {
        QueryWrapper<Video> queryWrapper=new QueryWrapper<Video>();
        queryWrapper.eq("chapter_id",id);
        videoMapper.delete(queryWrapper);
        int i = baseMapper.deleteById(id);
        if(i>0){
            return true;
        }
        return false;
    }

    @Override
    public List<ChapterVo> nestedListByCourseId(String courseId) {
        QueryWrapper<Video> videoQueryWrapper=new QueryWrapper<Video>();
        videoQueryWrapper.eq("course_id",courseId);
        List<Video> videos = videoMapper.selectList(videoQueryWrapper);
        QueryWrapper<Chapter> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("course_id",courseId);
        List<Chapter> chapters = baseMapper.selectList(queryWrapper);
        Map<String ,ChapterVo> map=new HashMap<>();

        for (Chapter chapter : chapters) {
            String chapterId = chapter.getId();
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);
            map.put(chapterId,chapterVo);
        }
        for (Video video : videos) {
            String chapterId = video.getChapterId();
            ChapterVo chapterVo = map.get(chapterId);
            VideoVo videoVo=new VideoVo();
            BeanUtils.copyProperties(video,videoVo);
            chapterVo.getChildren().add(videoVo);
        }
        Collection<ChapterVo> values = map.values();
        List<ChapterVo> chapterVos=new ArrayList<>(values);
        Collections.sort(chapterVos, (o1,o2)-> { return o1.getSort().compareTo(o2.getSort()); });
        return chapterVos;
    }
}
